package com.agent.user.aspect;

import com.agent.common.entity.UserContext;
import com.agent.common.utils.IpUtils;
import com.agent.user.annotation.AdminLog;
import com.agent.user.entity.AdminOperationLog;
import com.agent.user.service.AdminOperationLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 操作日志切面增强
 */
@Aspect
@Component
public class AdminOperationAspect {

    private final AdminOperationLogService logService;

    @Autowired
    public AdminOperationAspect(AdminOperationLogService logService) {
        this.logService = logService;
    }

    @AfterReturning(pointcut = "@annotation(adminLog)", returning = "result")
    public void logAdminOperation(JoinPoint joinPoint, AdminLog adminLog, Object result) {
        // 获取请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return;

        HttpServletRequest request = attributes.getRequest();

        // 获取管理员ID
        Long adminId = getCurrentAdminId();

        // 创建日志记录
        AdminOperationLog log = new AdminOperationLog();
        log.setAdminId(adminId);
        log.setAction(adminLog.value());
        log.setIpAddress(IpUtils.getClientIp(request));

        // 解析目标对象
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            // 尝试获取第一个参数作为目标ID
            if (args[0] instanceof Long) {
                log.setTargetId((Long) args[0]);
            }
            // 尝试获取带有id字段的对象
            else {
                for (Object arg : args) {
                    if (arg != null) {
                        try {
                            java.lang.reflect.Field idField = arg.getClass().getDeclaredField("id");
                            idField.setAccessible(true);
                            Object idValue = idField.get(arg);
                            if (idValue instanceof Long) {
                                log.setTargetId((Long) idValue);
                                break;
                            }
                        } catch (Exception e) {
                            // 忽略异常
                        }
                    }
                }
            }

            // 设置目标类型
            if (args[0] != null) {
                log.setTargetType(args[0].getClass().getSimpleName());
            }
        }

        // 记录操作
        logService.recordOperation(log);
    }

    private Long getCurrentAdminId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserContext) {
            UserContext userContext = (UserContext) authentication.getPrincipal();
            return userContext.getUserId();
        }
        return null;
    }
}